package v1

import (
	"github.com/gin-gonic/gin"
	"github.com/spectacleCase/develop_auth_platform/global"
	"github.com/spectacleCase/develop_auth_platform/models"
	request "github.com/spectacleCase/develop_auth_platform/models/request"
)

type Application struct{}

func (Application) Create() gin.HandlerFunc {
	return func(c *gin.Context) {
		var NewApp request.Create
		if err := c.ShouldBind(&NewApp); err != nil {
			models.FailWithMessage("参数有误", c)
			return
		}
		id, err := models.GenerateID()
		if err != nil {
			models.FailWithMessage(err.Error(), c)
			return
		}
		// 得到公私钥
		prKey, puKey, err := models.GetDefaultKeyPair()
		if err != nil {
			models.FailWithMessage(err.Error(), c)
			return
		}
		global.ApplicationList = append(global.ApplicationList, &models.Application{
			Id:          id,
			Name:        NewApp.Name,
			CallbackUrl: NewApp.CallbackUrl,
			PrKey:       prKey,
			PuKey:       puKey,
		})
		models.Ok(c)
		return
	}
}

func (Application) Get() gin.HandlerFunc {
	return func(c *gin.Context) {
		models.OkWithData(global.ApplicationList, c)
		return
	}
}

func (Application) Update() gin.HandlerFunc {
	return func(c *gin.Context) {
		var updateApp request.Update
		if err := c.ShouldBind(&updateApp); err != nil {
			models.FailWithMessage("参数有误", c)
			return
		}
		for index, app := range global.ApplicationList {
			if app == nil {
				continue // 跳过 nil 指针
			}
			if app.Id == updateApp.Id {
				app.Name = updateApp.Name
				app.CallbackUrl = updateApp.CallbackUrl
				global.ApplicationList[index] = app
			}
			models.Ok(c)
			return
		}

		models.FailWithMessage("错误的参数", c)
		return
	}
}

func (Application) Delete() gin.HandlerFunc {
	return func(c *gin.Context) {
		var delApp request.Delete
		if err := c.ShouldBind(&delApp); err != nil {
			models.FailWithMessage("参数有误", c)
			return
		}

		for index, app := range global.ApplicationList {
			if app == nil {
				continue // 跳过 nil 指针
			}
			if app.Id == delApp.Id {
				global.ApplicationList[index] = nil
			}
			models.Ok(c)
			return
		}
		models.FailWithMessage("错误的参数", c)
		return
	}
}
